# knowledge/examples/init_database.py

import os
import sys
import logging

# 添加项目根目录到Python路径
current_dir = os.path.dirname(os.path.abspath(__file__))
root_dir = os.path.dirname(os.path.dirname(current_dir))  # 向上两级到项目根目录
sys.path.insert(0, root_dir)  # 插入到路径开头

from knowledge.database.db_manager import DatabaseManager

def setup_logging():
    """配置日志"""
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )

def ensure_database_directory():
    """确保数据库目录存在"""
    database_dir = os.path.join(root_dir, "database")
    
    if not os.path.exists(database_dir):
        print(f"📁 创建数据库目录: {database_dir}")
        os.makedirs(database_dir, exist_ok=True)
    
    return database_dir

def main():
    print("✅ 企业知识库系统 v1.0.0 已加载")
    
    try:
        # 确保数据库目录存在
        database_dir = ensure_database_directory()
        db_path = os.path.join(database_dir, "enterprise_data.db")
        
        print(f"📁 数据库路径: {db_path}")
        print("🚀 初始化企业数据库...")
        
        # 使用绝对路径创建数据库管理器
        db_manager = DatabaseManager(db_path=db_path, verbose=True)
        
        # print("📊 创建模拟数据...")
        # db_manager.create_sample_data()
        
        # print("🎉 数据库初始化完成!")
        # print(f"📍 数据库文件: {db_path}")
        
        # 生成并保存数据库schema
        print("\n🔄 生成数据库Schema文件...")
        schema_json_file, latest_json_file, schema_text_file, latest_text_file = db_manager.getDBSchema()
        print(f"✅ Schema文件已保存:")
        print(f"   ├── JSON格式: {latest_json_file}")
        print(f"   └── 文本格式: {latest_text_file}")
        
        # 读取并显示文本格式的schema（用于确认内容）
        print(f"\n🔍 文本格式Schema预览:")
        print("-" * 60)
        with open(latest_text_file, 'r', encoding='utf-8') as f:
            content = f.read()
            # 只显示前1000字符作为预览
            preview = content[:1000] + "..." if len(content) > 1000 else content
            print(preview)
        
        # 验证数据库schema
        print("\n🔍 验证数据库结构...")
        schema = db_manager.get_database_schema()
        print(f"📊 数据库包含 {len(schema['tables'])} 个表:")
        for table in schema['tables']:
            print(f"  - {table['name']}: {table['description']} ({table['column_count']}个字段)")
        
        print(f"\n🔗 表关系数量: {len(schema['relationships'])}")
        for rel in schema['relationships']:
            print(f"  - {rel['from_table']}.{rel['from_column']} → {rel['to_table']}.{rel['to_column']}")
        
    except Exception as e:
        print(f"❌ 数据库初始化失败: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    setup_logging()
    main()